﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Auth.Application.Dtos;
using Auth.Application;
using Auth.Utility;
using Auth.Web.Models;
using SqlSugar;
using Auth.SqlSugar;
using System.Linq;
using Microsoft.AspNetCore.Http;

namespace Auth.Web.Controllers
{
    /// <summary>
    /// 功能管理控制器
    /// </summary>
    public class MenuController : AuthControllerBase
    {
        private readonly IMenuAppService _menuAppService;

        public MenuController(IMenuAppService menuAppService)
        {
            _menuAppService = menuAppService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult EditPage(string id, string pid)
        {

            bool isAdd = string.IsNullOrEmpty(id);
            id = string.IsNullOrEmpty(id) ? pid : id;
            ViewData["id"] = id;
            ViewData["isAdd"] = isAdd;
            return View();
        }
        /// <summary>
        /// 获取菜单JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenu()
        {
            var userId = HttpContext.Session.GetString("CurrentUserId");
            var menus = _menuAppService.GetMenusByUser(userId);
            return Json(menus);
        }

        /// <summary>
        /// 获取功能树JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuTreeData()
        {
            var menus = _menuAppService.GetAllList();
            List<TreeModel> treeModels = new List<TreeModel>();

            foreach (var menu in menus)
            {
                //区别菜单和按钮的图标
                var icon = menu.Type == 0 ? "" : "layui-icon layui-icon-fonts-strong";
                treeModels.Add(new TreeModel()
                {
                    Id = menu.Id,
                    Text = menu.Name,
                    Parent = menu.ParentId == Guid.Empty.ToString() ? "#" : menu.ParentId,
                    IconSkin = icon
                });
            }

            return Json(new ReturnModel() {Data = treeModels});
        }

        /// <summary>
        /// 获取表格头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetMenuTableCols()
        {
            List<LayuiColsModel> colsList = new List<LayuiColsModel>();
            colsList = GetTableCols<MenuDto>();
            return Json(new ReturnModel() {Data = colsList});
        }

        /// <summary>
        /// 获取子级功能列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetMneusByParent(string parentId, int page, int limit, string searchParam, string field, string order)
        {
            var orderField = string.Empty;
            if (!string.IsNullOrEmpty(field))
                orderField = field + " " + order;
            List<IConditionalModel> conModels = ConditionHelper.GetCondition(searchParam);
            conModels.Add(new ConditionalModel()
            {
                FieldName = "parentId",
                ConditionalType = ConditionalType.LikeLeft,
                FieldValue = parentId
            });
            var result = _menuAppService.GetTableList(page, limit, conModels, orderField);
            return Ok(result);
        }

        /// <summary>
        /// 新增或编辑功能
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Edit(MenuDto dto)
        {
            var result = new ReturnModel();
            if (!ModelState.IsValid)
            {
                result.Msg = GetModelStateError();
                return Json(result);
            }

            if (_menuAppService.InsertOrUpdate(dto))
            {
                result.Success = true;
                return Json(result);
            }

            return Json(result);
        }

        [HttpPost]
        public IActionResult DeleteMuti(string ids)
        {
            ReturnModel res = new ReturnModel();
            try
            {
                string[] idArray = ids.Split(',');
                var delIds = idArray.Where(s => !string.IsNullOrEmpty(s)).ToList();
                _menuAppService.Delete(delIds);
                res.Msg = "删除成功";
                res.Success = true;
                return Json(res);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public ActionResult Get(string id, bool isAdd)
        {
            var menu = new MenuDto();
            if (!isAdd)
            {
                menu = _menuAppService.QuerySingle(id);
            }
            else
            {
                menu.ParentId = id;
                menu.No = _menuAppService.GetNextNo(id);
            }

            return Json(new ReturnModel() {Data = menu});
        }
    }

}